<template>
  <div class="behavior-container">
    <!-- 搜索和筛选区域 -->
    <div class="filter-area">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户ID或用户名"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      
      <el-select v-model="filterType" placeholder="行为类型" style="width: 120px; margin-right: 10px">
        <el-option label="全部" value="all"></el-option>
        <el-option label="发帖" value="post"></el-option>
        <el-option label="评论" value="comment"></el-option>
        <el-option label="点赞" value="like"></el-option>
        <el-option label="收藏" value="favorite"></el-option>
        <el-option label="违规" value="violation"></el-option>
      </el-select>
      
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 300px; margin-right: 10px"
      ></el-date-picker>
      <!-- 添加导出 Excel 按钮 -->
      <el-button 
        type="primary" 
        icon="el-icon-download"
        @click="exportToExcel"
        style="margin-left: 10px"
      >
        导出Excel
      </el-button>
    </div>

    <!-- 用户行为表格 -->
    <el-table :data="filteredBehaviors" border style="width: 100%">
      <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="type" label="行为类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="getBehaviorTagType(scope.row.type)">
            {{ getBehaviorTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容摘要"></el-table-column>
      <el-table-column prop="time" label="时间" width="180"></el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="warning" 
            v-if="scope.row.status === '违规'"
            @click="handleWarn(scope.row)"
          >
            警告
          </el-button>
          <el-button 
            size="mini" 
            :type="scope.row.status === '封禁' ? 'success' : 'danger'"
            @click="handleBan(scope.row)"
          >
            {{ scope.row.status === '封禁' ? '解封' : '封禁' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalBehaviors"
    ></el-pagination>
  </div>
</template>

<script>
// 导入导出工具
import { exportJsonToExcel } from '@/utils/export2Excel'

export default {
  name: 'UserBehaviorManagement',
  data() {
    return {
      behaviors: [
        // 模拟数据
        {
          id: 1,
          userId: 101,
          username: '张三',
          type: 'post',
          content: '发布了帖子《关于抑郁症的自我调节方法》',
          time: '2023-05-15 14:30:22',
          status: '正常'
        },
        {
          id: 2,
          userId: 102,
          username: '李四',
          type: 'comment',
          content: '评论了帖子《焦虑症的症状有哪些》："非常有用！"',
          time: '2023-05-14 09:15:45',
          status: '正常'
        },
        {
          id: 3,
          userId: 103,
          username: '王五',
          type: 'violation',
          content: '发布了违规内容《虚假药品广告》',
          time: '2023-05-13 16:20:10',
          status: '违规'
        },
        // 可以添加更多模拟数据
      ],
      searchQuery: '',
      filterType: 'all',
      dateRange: [],
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    filteredBehaviors() {
      return this.behaviors.filter(behavior => {
        const matchesSearch = behavior.userId.toString().includes(this.searchQuery) || 
                            behavior.username.includes(this.searchQuery) ||
                            behavior.content.includes(this.searchQuery)
        
        const matchesType = this.filterType === 'all' || behavior.type === this.filterType
        
        let matchesDate = true
        if (this.dateRange && this.dateRange.length === 2) {
          const startDate = new Date(this.dateRange[0])
          const endDate = new Date(this.dateRange[1])
          const behaviorDate = new Date(behavior.time)
          
          matchesDate = behaviorDate >= startDate && behaviorDate <= endDate
        }
        
        return matchesSearch && matchesType && matchesDate
      })
    },
    totalBehaviors() {
      return this.filteredBehaviors.length
    }
  },
  methods: {
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    getBehaviorTypeName(type) {
      const typeMap = {
        'post': '发帖',
        'comment': '评论',
        'like': '点赞',
        'favorite': '收藏',
        'violation': '违规'
      }
      return typeMap[type] || type
    },
    getBehaviorTagType(type) {
      const typeMap = {
        'post': '',
        'comment': 'info',
        'like': 'success',
        'favorite': 'warning',
        'violation': 'danger'
      }
      return typeMap[type] || ''
    },
    handleWarn(row) {
      this.$confirm('确定要警告该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success(`已向用户 ${row.username} 发送警告`)
      })
    },
    handleBan(row) {
      const newStatus = row.status === '封禁' ? '正常' : '封禁'
      const action = newStatus === '封禁' ? '封禁' : '解封'
      
      this.$confirm(`确定要${action}该用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = newStatus
        this.$message.success(`已${action}用户 ${row.username}`)
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    // 实现导出 Excel 方法
    exportToExcel() {
      const tHeader = ['用户ID', '用户名', '行为类型', '内容摘要', '时间', '状态']
      const filterVal = ['userId', 'username', 'type', 'content', 'time', 'status']
      const data = this.filteredBehaviors.map(behavior => filterVal.map(key => {
        if (key === 'type') {
          return this.getBehaviorTypeName(behavior[key])
        }
        return behavior[key]
      }))
      
      exportJsonToExcel(tHeader, data, '用户行为列表')
    }
  }
}
</script>

<style scoped>
.behavior-container {
  padding: 20px;
}

.filter-area {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>